package com.yww.datastructure.deque;

import java.util.Iterator;

/**
 * @author yww
 * @description 循环数组实现双端队列
 * @since 2024/2/5 15:46
 */
public final class ArrayDeque<E> implements Deque<E> {
    private int head;
    private int tail;
    private final E[] array;

    public ArrayDeque() {
        this(10);
    }

    @SuppressWarnings("unchecked")
    public ArrayDeque(int capacity) {
        // 需要预留一个位置给tail判断满
        this.array = (E[]) new Object[capacity + 1];
    }

    @Override
    public boolean offerFirst(E e) {
        if (isFull()) {
            return false;
        }
        // 往首添加，head先循环自减，再添加
        head = dec(head);
        array[head] = e;
        return true;
    }

    @Override
    public boolean offerLast(E e) {
        if (isFull()) {
            return false;
        }
        // 往尾添加，先添加，tail后循环自增
        array[tail] = e;
        tail = inc(tail);
        return true;
    }

    @Override
    public E pollFirst() {
        if (isEmpty()) {
            return null;
        }
        // 弹出首，先弹出head，head再循环自增
        E polled = array[head];
        array[head] = null; // help gc
        head = inc(head);
        return polled;
    }

    @Override
    public E pollLast() {
        if (isEmpty()) {
            return null;
        }
        // 弹出未，tail先循环自减，再弹出
        tail = dec(tail);
        E polled = array[tail];
        array[tail] = null; // help gc
        return polled;
    }

    @Override
    public E peekFirst() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public E peekLast() {
        if (isEmpty()) {
            return null;
        }
        return array[dec(tail)];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        if (head > tail) {
            return head - tail == 1;
        } else if (tail > head) {
            return tail - head == array.length - 1;
        }
        return false;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E val = array[p];
                p = inc(p);
                return val;
            }
        };
    }

    // 循环数组索引的自增和自减
    private int inc(int index) {
        if (index + 1 > array.length - 1) {
            return 0;
        }
        return index + 1;
    }

    private int dec(int index) {
        if (index - 1 < 0) {
            return array.length - 1;
        }
        return index - 1;
    }
}
